/*
 * Copyright (c) 2008 Anshuman Manur <anshuman.manur@gmail.com>,
 * Lavanya Shastri <lavanya.shastri@gmail.com>
 * 
 * This file is part of Andronova.
 * 
 * Andronova is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 * 
 * Andronova is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *  
 * You should have received a copy of the GNU General Public License
 * along with Andronova.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * This file may use the functionality provided by the library
 * jid3lib version 0.5.4 (<http://sourceforge.net/projects/javamusictag/>).
 * jid3lib and its uses are covered by GNU Lesser General Public License.
 * 
 */

package com.googlecode.andronova;

import java.io.FileNotFoundException;
import java.io.IOException;

import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.SubMenu;
import android.view.View;
import android.view.Menu.Item;
import android.view.View.OnKeyListener;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

import com.googlecode.andronova.helper.DBConstants;
import com.googlecode.andronova.helper.PlayBackOrganiser;
import com.googlecode.andronova.helper.PlayList;
import com.googlecode.andronova.helper.Song;

public class PlaylistEditor extends ListActivity {

	private static final String MITEM_NAME_ADD = "Add";
	private static final String MITEM_NAME_REMOVE = "Remove";
	private static final String MITEM_NAME_CLEAR = "Clear";
	private static final String MITEM_NAME_MOVE = "Move";
	private static final String MITEM_SUBMENU_NAME_MUTATE = "Mutate";
	
	private static final String MITEM_NAME_DONE = "Done";
	private static final String MITEM_NAME_HELP = "Help";
	private static final String MITEM_NAME_TAGEDITOR = "Tag Editor";
	private static final String MITEM_NAME_LIBRARY = "Library";
	private static final String MITEM_NAME_EXIT = "Exit";
	
	private static final int MITEM_ID_ADD = 6;
	private static final int MITEM_ID_REMOVE = 7;
	private static final int MITEM_ID_CLEAR = 8;
	private static final int MITEM_ID_MOVE = 9;
	private static final int MITEM_SUBMENU_ID_MUTATE = 0;
	
	private static final int MITEM_ID_DONE = 1;
	private static final int MITEM_ID_EXIT = 2;	
	private static final int MITEM_ID_TAGEDITOR = 3;
	private static final int MITEM_ID_LIBRARY = 4;
	private static final int MITEM_ID_HELP = 5;
		
	private static final int M_GID_PL_MUTATE = 1;
	private static final int M_GID_DONE = 2;
	private static final int M_GID_GENERAL = 3;
	private static final int M_GID_HELP = 4;
	
	private int mode = MODE_NORMAL;
	
	private static final int MODE_NORMAL = 0;
	private static final int MODE_MOVE = 1;
	private static final int MODE_REMOVE = 2;
	
	private boolean selected = false;
	private long selectedId;
	private int fromPosition;
	
	private PlayList playlist;
	
	private Cursor c;
	
	private SimpleCursorAdapter adapter;
	
	private Context ctx;
	private Handler myHandler;
	
	@Override
	protected void onCreate(Bundle icicle) {
		super.onCreate(icicle);		
		setTitle("Playlist");
		myHandler = new Handler();
		ctx = this;
		
		SQLiteDatabase db;
		try {
			db = this.openDatabase(DBConstants.DB_NAME, null);
		}
		catch(FileNotFoundException fe) {
			try {
				db = this.createDatabase(DBConstants.DB_NAME, DBConstants.DB_VERSION, MODE_PRIVATE, null);
				db.execSQL(DBConstants.LIB_TABLE_CREATE);
				db.execSQL(DBConstants.PLED_TABLE_CREATE);
			}
			catch(final Exception e) {
				myHandler.post(new Runnable() {
					public void run() {
						ctx.showAlert(
								"Error", 
								android.R.id.appIcon, 
								"Unable to create Database\n" + e.toString(), 
								"OK",
								new android.content.DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog, int which) {
										finish();
									}
								},
								false,
								null);
					}
				});
				db = null;
			}
		}
		
		playlist = new PlayList(db);		
		c = playlist.getCursor(null);
		adapter = new SimpleCursorAdapter(this,  R.layout.pl_layout,  c, new String[] { DBConstants.CNAME_TITLE, DBConstants.CNAME_ARTIST },  new int[] { R.id.text1, R.id.text2 });
		setListAdapter(adapter);
		
		getListView().setOnKeyListener(new OnKeyListener() {
			
			public boolean onKey(View v, int keyCode, KeyEvent keyEvent) {
				if(mode != MODE_MOVE)
					return false;
				
				if(!selected)
					return false;
				
				if(keyEvent.getAction() != KeyEvent.ACTION_UP)
					return false;
				
				long toId;
				if(keyCode == KeyEvent.KEYCODE_DPAD_UP) {
					if(fromPosition == 0)
						return true;
					c.moveTo(fromPosition-1);
					toId = c.getLong(c.getColumnIndex(DBConstants.CNAME_ID));
					playlist.move(selectedId, toId);
					c.requery();
					selectedId = toId;
					fromPosition--;
					return true;
				}
				else if(keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
					if(fromPosition == c.count()-1)
						return true;
					c.moveTo(fromPosition+1);
					toId = c.getLong(c.getColumnIndex(DBConstants.CNAME_ID));
					playlist.move(selectedId, toId);
					c.requery();
					selectedId = toId;
					fromPosition++;
					return true;
				}
				return false;
			}
		});
	}
	
	
	@Override
	protected void onResume() {
		super.onResume();		
		c.requery();
	}




	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		
		switch(mode) {
		case MODE_NORMAL:
			try {
				Song s = playlist.getSong(id);				
				if(Playback.pbOrganiser==null || !Playback.pbOrganiser.isPlayListMode())
					Playback.pbOrganiser = new PlayBackOrganiser(playlist);
				Playback.pbOrganiser.setCurrentSong(s);
				this.setResult(RESULT_OK);
				this.finish();
			}
			catch(Exception e) {
				//TODO: pop-up
			}
			break;
			
		case MODE_REMOVE:
			playlist.remove(id);
			c.requery();
			break;
			
		case MODE_MOVE:
			selected = !selected;
			if(selected) {
				selectedId = id;
				fromPosition = position;
			}
			break;
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onPrepareOptionsMenu(menu);
		
		menu.add(M_GID_DONE, MITEM_ID_DONE, MITEM_NAME_DONE,  
				R.drawable.andro_done);
		menu.add(M_GID_HELP, MITEM_ID_HELP, MITEM_NAME_HELP,  
				R.drawable.andro_help);
		menu.add(M_GID_GENERAL, MITEM_ID_TAGEDITOR, MITEM_NAME_TAGEDITOR,  
				R.drawable.andro_tageditor);
		menu.add(M_GID_GENERAL, MITEM_ID_LIBRARY, MITEM_NAME_LIBRARY, 
				R.drawable.andro_library);
		menu.add(M_GID_GENERAL, MITEM_ID_EXIT, MITEM_NAME_EXIT,
				R.drawable.andro_exit);
		
		SubMenu subMenu = menu.addSubMenu(M_GID_PL_MUTATE, MITEM_SUBMENU_ID_MUTATE, MITEM_SUBMENU_NAME_MUTATE, 
				R.drawable.andro_mutate);
		subMenu.add(M_GID_PL_MUTATE, MITEM_ID_ADD, MITEM_NAME_ADD,  
				R.drawable.andro_add);
		subMenu.add(M_GID_PL_MUTATE, MITEM_ID_REMOVE, MITEM_NAME_REMOVE,  
				R.drawable.andro_remove);
		subMenu.add(M_GID_PL_MUTATE, MITEM_ID_CLEAR, MITEM_NAME_CLEAR,  
				R.drawable.andro_clear);
		subMenu.add(M_GID_PL_MUTATE, MITEM_ID_MOVE, MITEM_NAME_MOVE,  
				R.drawable.andro_move);		
		
		return true;
	}


	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		super.onPrepareOptionsMenu(menu);
		
		if(mode == MODE_NORMAL) {
			menu.setItemShown(MITEM_ID_DONE, false);
			menu.setGroupShown(M_GID_PL_MUTATE, true);
			menu.setGroupShown(M_GID_GENERAL, true);
		}
		else if(mode==MODE_REMOVE || mode==MODE_MOVE) {
			menu.setGroupShown(M_GID_PL_MUTATE, false);
			menu.setItemShown(MITEM_ID_DONE, true);
			menu.setGroupShown(M_GID_GENERAL, false);
		}
		
		return true;
	}


	@Override
	public boolean onOptionsItemSelected(Item item) {
		super.onOptionsItemSelected(item);
		
		switch(item.getId()) {
		case MITEM_ID_ADD:
			Intent i = new Intent(this, LibraryActivity.class);
			i.putExtra("" + R.string.MODE, true);
			startSubActivity(i, PlayScreen.PICK_SONG);
			break;
		
		case MITEM_ID_REMOVE:
			mode = MODE_REMOVE;
			break;
			
		case MITEM_ID_MOVE:
			mode = MODE_MOVE;
			break;
			
		case MITEM_ID_CLEAR:
			playlist.clear();
			c.requery();
			break;
			
		case MITEM_ID_DONE:
			mode = MODE_NORMAL;
			selected = false;
			break;
			
		case MITEM_ID_HELP:
			Help.CALLING_ACTIVITY = Help.PLAYLIST_EDITOR;
 			Intent e = new Intent(this,  Help.class);
 			startActivity(e);
			break;
			
		case MITEM_ID_TAGEDITOR:
			try {
				long id = this.getSelectedItemId();
				Song s = playlist.getSong(id);
				TagEditor.s = s;
				Intent i9 = new Intent(this, TagEditor.class);
				startActivity(i9);
			}
			catch(IOException E) {
				this.showAlert("Error", android.R.id.appIcon, "Cannot read from file\n" + E.toString(), "OK", false);
			}
			break;
			
		case MITEM_ID_LIBRARY:
			Intent i11 = new Intent(this, LibraryActivity.class);
			startActivity(i11);
			finish();
			break;
			
		case MITEM_ID_EXIT:
			finish();
			break;
		}
		
		return true;
	}


	@Override
	protected void onActivityResult(int requestCode, int resultCode,
			String data, Bundle extras) {
		super.onActivityResult(requestCode, resultCode, data, extras);
		
		switch(requestCode) {
		case PlayScreen.PICK_SONG:
			if(resultCode == RESULT_OK) {
				c.requery();
				playlist.setMaxId();
			}
			break;
		}
	}
	
	
}
